document.write("<script type='text/javascript' src='/js/abi.js'></script>");

var web3;
var privateKey = "c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3";
var gasPrice;

App = {
    web3Provider: null,
    contracts: {},
    init: function () {
        return App.initWeb3();
    },

    initWeb3: function () {


        // Initialize web3 and set the provider to the testRPC.
        if (typeof web3 !== 'undefined') {
            App.web3Provider = web3.currentProvider;
            web3 = new Web3(web3.currentProvider);
        } else {
            // set the provider you want from Web3.providers
            // App.web3Provider = new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws');
            App.web3Provider = new Web3.providers.HttpProvider('https://ropsten.infura.io/c8LMJFLLL7rUEBtxozvJ');
            web3 = new Web3(App.web3Provider);
        }
        return App.initContract();
    }
    ,

    initContract: function () {

        // 通过ABI和地址获取已部署的合约对象
        App.contracts.RecreationChain = new web3.eth.Contract(abi, address);
        App.contracts.RecreationChain.setProvider(App.web3Provider);
        App.create();

    }
    ,

    bindEvents: function () {
        $(document).on('click', '#transferButton', App.handleTransfer);
    }
    ,

    //创建钱包地址
    create: function () {
        var account_1 = web3.eth.accounts.create("123456");
        console.log(account_1.address);
    },

    handleTransfer: function (event) {
        event.preventDefault();

        var amount = parseInt($('#TTTransferAmount').val());
        var b = amount + "000000000000000000";


        //var amount = new Number(num.toFixed());


        var toAddress = $('#TTTransferAddress').val();

        console.log('Transfer ' + amount + ' TT to ' + toAddress);


        web3.eth.getGasPrice().then(function (result) {
            gasPrice = result;
            console.log("gasPrice==========" + gasPrice);
        });

        console.log("--------" + App.contracts.RecreationChain.methods.transfer(toAddress, b).encodeABI());

        web3.eth.estimateGas({
            form: "0x02E784F79fb59249B51EFD166cf57f1D76A88900",
            to: toAddress,
            data: App.contracts.RecreationChain.methods.transfer(toAddress, b).encodeABI()
        }).then(function (res) {
            console.log("gas--------" + res);

            web3.eth.accounts.signTransaction({
                to: address,
                form: "0x02E784F79fb59249B51EFD166cf57f1D76A88900",
                data: App.contracts.RecreationChain.methods.transfer(toAddress, b).encodeABI(),
                gasPrice: gasPrice,
                gas: 50000
            }, '0x304649b6f99ab6c43bfc1b88eadfd97663814e1d0c7bc2bf2b32810b1dd33b99').then(function (res) {
                console.log(res.rawTransaction);
                web3.eth.sendSignedTransaction(res.rawTransaction).then(function (res) {
                    console.log(res);

                });
            });

        })
        ;


    }

    ,


    getBalances: function () {
        console.log('Getting balances...');

        web3.eth.getAccounts(function (error, accounts) {
            if (error) {
                console.log(error);
            }
            // var account = accounts[0];
            var account = "0x02E784F79fb59249B51EFD166cf57f1D76A88900";

            App.contracts.RecreationChain.methods.balanceOf(account).call(function (err, result) {
                var balance = web3.utils.fromWei(result, 'ether');
                if (!err) {
                    $('#TTBalance').text(balance);
                } else {
                    console.log(err);
                }
            });

        });
    }
    ,

    encrypt: function () {
        console.log('encrypt...');
        //'c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3', '12345678'
        console.log(web3.version);
        var str = web3.eth.accounts.encrypt("304649b6f99ab6c43bfc1b88eadfd97663814e1d0c7bc2bf2b32810b1dd33b99", "123456");
        //转json字符串
        var homeObj = JSON.stringify(str);
        console.log(homeObj)
        // $('#str').text(homeObj);


    }
    ,

    myMonitorEvent: function () {
        console.log(web3.eth.givenProvider);
        var eventinfo = web3.eth.abi.encodeEventSignature({
                name: 'Transfer',
                type: 'event',
                inputs: [
                    {
                        "indexed": true,
                        "name": "from",
                        "type": "address"
                    },
                    {
                        "indexed": true,
                        "name": "to",
                        "type": "address"
                    },
                    {
                        "indexed": false,
                        "name": "value",
                        "type": "uint256"
                    }
                ]
            }
        );
        console.log("encodeEventSignature===================" + eventinfo);
        // 获取事件对象
        App.contracts.RecreationChain.events.Transfer({
            filter: {fromBlock: 0, toBlock: 'latest', address: '0xa29a7937a26a031939fa02317caf800f1b0487f2'},
            fromBlock: 0,
            topics: [eventinfo]
        }, function (error, event) {
            if (!error) {
                console.log("event===================" + event);
            } else {
                console.log(error);
            }
        }).on('data', function (event) {
            console.log("dataevent===================" + event);
        }).on('changed', function (event) {
            console.log("changedevent===================" + event);
        }).on('error', function (event) {
            console.log("errorevent===================" + event);
        });

    }

    ,
    mySubscriptionEvent: function () {

        // var event_ = web3.eth.abi.encodeEventSignature({
        //         name: 'Transfer',
        //         type: 'event',
        //         inputs: [
        //             {
        //                 "indexed": true,
        //                 "name": "from",
        //                 "type": "address"
        //             },
        //             {
        //                 "indexed": true,
        //                 "name": "to",
        //                 "type": "address"
        //             },
        //             {
        //                 "indexed": false,
        //                 "name": "value",
        //                 "type": "uint256"
        //             }
        //         ]
        //     }
        // );
        // console.log("encodeEventSignature===================" + event_);
        web3.eth.subscribe('newBlockHeaders', function (error, result) {
            if (!error) {
                console.log(result);
            } else {
                console.log(error);
            }
        }).on("data", function (blockHeader) {
            // will return the block number.
            console.log(blockHeader.number);
        });
        // // 获取事件对象
        //
        // web3.eth.subscribe('logs', {
        //     fromBlock: 0,
        //     address: '0xa29a7937a26a031939fa02317caf800f1b0487f2',
        //     topics: [event_]
        // }, function (error, result) {
        //     if (!error)
        //         console.log("subscribeEvent===================" + result);
        // }).on("data", function (log) {
        //     console.log("logEvent===================" + log);
        // }).on("changed", function (log) {
        //     console.log("changedEvent===================" + log);
        // });

    }
}
;

$(function () {
    $(window).load(function () {
        App.init();
    });
});



